package client;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.naming.*;

import rmi.Estampille;
import rmi.Message;
import rmi.MessageRemote;
import rmi.ClientRmiInterfaceImp;


import gui.TableauBlancUI;

public class Client extends Thread implements Serializable{
	/**
	 * classe client
	 */
	private static final long serialVersionUID = 1L;
	private TableauBlancUI tb;
	private Estampille estampille;
	private ArrayList<Message> list;
	


	public Client(){
		
		this.tb = new TableauBlancUI();
		this.estampille = new Estampille();
		this.list=new ArrayList<Message>();
		
	}

	public ArrayList<Message> getList() {
		return list;
	}
	public TableauBlancUI getTb() {
		return tb;
	}

	public Estampille getEstampille(){
		return estampille;
	}
	
	public void setEstampille(Estampille estampille){
		this.estampille=estampille;
	}
    public void quit()
    {
    	
			try {
				getTb().getMr().getCtx().close();
				System.out.println("client "+getTb().getId()+" est quit");
				System.exit(1);
			} catch (NamingException e) {
				
				e.printStackTrace();
			}
			
    	
    }


	public void initservice(int id,Client c)
	{
		try {
			// Set properties
		    Hashtable<String,String> env = new Hashtable<String,String>(11);
	
		    // Definition of the jndi server
		    env.put(Context.INITIAL_CONTEXT_FACTORY,
			    "com.sun.jndi.rmi.registry.RegistryContextFactory");
		    env.put(Context.PROVIDER_URL, "rmi://localhost:2999");
	
		    // Get the initial context
	        Context ctx = new InitialContext(env);
	        ClientRmiInterfaceImp rmiImp=new ClientRmiInterfaceImp(this);
		    ctx.rebind("cl"+id,rmiImp) ;
		    
	
		    //System.out.println("Serveur pret...."); 
		    
		}
		catch (Exception re) {
		    
		    System.out.println("Exception 1 " + re) ; 
		}
	}
	public void run()
	{
		try {
			
		    MessageRemote mr = new MessageRemote();
		   
		    int id = mr.enregistre(this) ; 
		    this.getTb().setMr(mr);
		    this.getTb().setPro(mr.getPro());
		    System.out.println("Client Id: "+id);  
		    this.getTb().setId(id); 
		    this.initservice(id,this);
		    
		    
		}
		catch (Exception e) {
		    System.out.println(e) ; 
		}
	}
	public static void main(String [] args) 
    {
		
    }
}
